class AdminsController < ApplicationController
  before_filter :find_admin, :only => [:show, :edit, :update, :destroy]
  before_filter :est_connecte, :only => [:edit, :update, :destroy]
  before_filter :est_proprietaire, :only => [:edit, :update, :destroy]
  before_filter :disconnecte, :only => [:new]

  def find_admin
    @admin = Admin.find(params[:id])
    @user = @admin.user
  end

  def new
    @admin = Admin.new
    @user = User.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @admin }
    end
  end

  def create
    @admin = Admin.new(params[:admin])
    @user = @admin.build_user(params[:admin][:user_attributes])
    respond_to do |format|
      if @admin.save
        @template.sign_in @user
        flash[:notice] = "L'inscription de l'admin est réussi"
        format.html { redirect_to @admin }
        format.xml  { render :xml => @admin, :status => :created, :location => @admin }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @admin.errors, :status => :unprocessable_entity }
      end
    end
  end

  def edit

  end

  def update
    respond_to do |format|
      if @admin.update_attributes(params[:admin])
        flash[:notice] = 'Admin was successfully updated.'
        format.html { redirect_to(@admin) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @admin.errors, :status => :unprocessable_entity }
      end
    end
  end

  def index
    @admins = Admin.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @admins }
    end
  end

  def show
    respond_to do |format|
      format.html # _question.html.erb
      format.xml  { render :xml => @admin }
    end
  end

  def destroy
    @admin.destroy

    respond_to do |format|
      format.html { redirect_to(admins_url) }
      format.xml  { head :ok }
    end
  end

  private

  def est_connecte
    unless @template.signed_in?
      flash[:notice] = "Veuillez-vous connecter pour accéder à cette page."
      redirect_to connexion_path
    end
  end

  def est_proprietaire
    unless @template.current_user == @user
      flash[:notice] = "Vous n'avez pas le droit d'accéder à cette page."
      begin
        redirect_to :back
      rescue ActionController::RedirectBackError
        redirect_to root_path
      end
    end
  end

  def disconnecte
    if @template.signed_in?
      flash[:notice] = "Veuillez-vous déconnecter pour accéder à cette page."
      begin
        redirect_to :back
      rescue ActionController::RedirectBackError
        redirect_to root_path
      end
    end
  end
end
